// 创建 Toast 容器
function createToastContainer() {
    let container = document.getElementById('toast-container');
    if (!container) {
        container = document.createElement('div');
        container.id = 'toast-container';
        container.className = 'position-fixed top-0 end-0 p-3';
        container.style.zIndex = '9999';
        document.body.appendChild(container);
    }
    return container;
}

// 显示 Toast 提示
function showToast(message, type = 'info') {
    const container = createToastContainer();
    const toast = document.createElement('div');

    // 设置 Toast 类型对应的颜色
    const typeClass = {
        'success': 'bg-success',
        'error': 'bg-danger',
        'warning': 'bg-warning',
        'info': 'bg-info'
    }[type] || 'bg-info';

    toast.className = `toast align-items-center text-white ${typeClass} border-0`;
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');

    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">
                ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
    `;

    container.appendChild(toast);

    const bsToast = new bootstrap.Toast(toast, {
        autohide: true,
        delay: 3000
    });

    bsToast.show();

    // 监听隐藏事件，移除 DOM 元素
    toast.addEventListener('hidden.bs.toast', () => {
        toast.remove();
    });
}



// 创建全局 Loading
let currentLoadingTimeout = null;

function createLoadingContainer() {
    let container = document.getElementById('global-loading-container');
    if (!container) {
        container = document.createElement('div');
        container.id = 'global-loading-container';
        container.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        `;

        const loadingContent = document.createElement('div');
        loadingContent.className = 'loading-content';
        loadingContent.style.cssText = `
            background: white;
            padding: 2rem;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            max-width: 80%;
        `;

        const spinner = document.createElement('div');
        spinner.className = 'spinner-border text-primary mb-3';
        spinner.setAttribute('role', 'status');

        const loadingText = document.createElement('div');
        loadingText.id = 'loading-text';
        loadingText.className = 'mt-2';
        loadingText.style.color = '#566a7f';

        loadingContent.appendChild(spinner);
        loadingContent.appendChild(loadingText);
        container.appendChild(loadingContent);
        document.body.appendChild(container);
    }
    return container;
}

// 显示 Loading
function showLoading(text = '加载中...') {
    // 如果有正在显示的 loading，先清除
    if (currentLoadingTimeout) {
        clearTimeout(currentLoadingTimeout);
        currentLoadingTimeout = null;
    }

    const container = createLoadingContainer();
    const loadingText = document.getElementById('loading-text');

    // 更新文本
    loadingText.innerHTML = text;

    // 显示 loading
    container.style.display = 'flex';

    // 禁用页面滚动
    document.body.style.overflow = 'hidden';

    // 添加淡入效果
    currentLoadingTimeout = setTimeout(() => {
        container.style.opacity = '1';
    }, 10);
}

// 隐藏 Loading
function hideLoading() {
    const container = document.getElementById('global-loading-container');
    if (container) {
        // 清除可能存在的 timeout
        if (currentLoadingTimeout) {
            clearTimeout(currentLoadingTimeout);
            currentLoadingTimeout = null;
        }

        // 添加淡出效果
        container.style.opacity = '0';

        // 延迟后完全隐藏
        setTimeout(() => {
            container.style.display = 'none';
            // 恢复页面滚动
            document.body.style.overflow = '';
        }, 300);
    }
}

// 添加样式到页面
function addLoadingStyles() {
    const style = document.createElement('style');
    style.textContent = `
        #global-loading-container {
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .loading-content {
            transform: translateY(20px);
            animation: slideUp 0.3s ease forwards;
        }
        
        @keyframes slideUp {
            to {
                transform: translateY(0);
            }
        }
        
        .spinner-border {
            width: 3rem;
            height: 3rem;
        }
    `;
    document.head.appendChild(style);
}

// 页面加载时添加样式
document.addEventListener('DOMContentLoaded', addLoadingStyles);


// 解密
function decrypt(encryptedData) {
    // 待解码的字符串（从 Python 编码结果而来）
    const encodedString = encryptedData;

    // 进行 Base64 解码
    const decodedBytes = atob(encodedString);
    // 将解码后的字符串转换为 Uint8Array
    const byteArray = new Uint8Array(decodedBytes.length);
    for (let i = 0; i < decodedBytes.length; i++) {
        byteArray[i] = decodedBytes.charCodeAt(i);
    }
    // 使用 TextDecoder 转换为字符串
    const decodedString = new TextDecoder().decode(byteArray);
    return decodedString;

}



// 判断是否是base64加密的值
function isBase64(str) {
    try {
        return btoa(atob(str)) === str;
    } catch (err) {
        return false;
    }
}

// 设置cookie
function setCookie(name, value) {
    document.cookie = `${name}=${value}`; // 设置cookie
}

// 获取cookie
function getCookie(name) {
    const cookie = document.cookie;
    const cookieArray = cookie.split(';');
    for (let i = 0; i < cookieArray.length; i++) {
        const cookieItem = cookieArray[i].trim();
        if (cookieItem.startsWith(name + '=')) {
            return cookieItem.split('=')[1];
        }
    }
    return null;
}

// 设置session
function setSession(name, value) {
    sessionStorage.setItem(name, value);
}

// 获取session
function getSession(name) {
    return sessionStorage.getItem(name);
}

// 删除session
function removeSession(name) {
    sessionStorage.removeItem(name);
}

// 显示确认框
function showConfirm(options = {}) {
    /**
     * const confirmed = await showConfirm({
        title: '删除确认',
        message: '确定要删除这个用户吗？此操作不可恢复！',
        type: 'danger',
        confirmText: '删除',
        confirmButtonClass: 'btn-danger'
    });
    
    if (confirmed) {
        // 执行删除操作
        deleteUser(userId);
    }
     */
    return new Promise((resolve, reject) => {
        const {
            title = '确认',
            message = '确定要执行此操作吗？',
            confirmText = '确定',
            cancelText = '取消',
            type = 'warning', // success, warning, danger, info
            confirmButtonClass = 'btn-primary'
        } = options;

        // 创建确认框容器
        const modalId = 'confirm-modal-' + Date.now();
        const modalHtml = `
            <div class="modal fade" id="${modalId}" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class='bx ${getIconByType(type)} me-2'></i>
                                ${title}
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            ${message}
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">
                                ${cancelText}
                            </button>
                            <button type="button" class="btn ${confirmButtonClass}" id="confirm-btn">
                                ${confirmText}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // 添加到页面
        const modalContainer = document.createElement('div');
        modalContainer.innerHTML = modalHtml;
        document.body.appendChild(modalContainer);

        // 获取modal元素
        const modalElement = document.getElementById(modalId);
        const modal = new bootstrap.Modal(modalElement);

        // 确认按钮点击事件
        document.getElementById('confirm-btn').addEventListener('click', () => {
            modal.hide();
            resolve(true);
        });

        // 取消按钮点击事件
        modalElement.addEventListener('hidden.bs.modal', () => {
            modalElement.remove();
            resolve(false);
        });

        // 显示modal
        modal.show();
    });
}

// 根据类型获取图标
function getIconByType(type) {
    const icons = {
        'success': 'bx-check-circle text-success',
        'warning': 'bx-error-circle text-warning',
        'danger': 'bx-x-circle text-danger',
        'info': 'bx-info-circle text-info'
    };
    return icons[type] || icons['warning'];
}

